var express = require('express');
var router = express.Router();
var bodyParser = require('body-parser');
var Log = require('../utils/logger');
var dbManager = require('../utils/db-manager');
var ObjectID = require('mongodb').ObjectID;
var path = require('path');

var upload = require('../utils/upload');

router.use(bodyParser.json()); // for parsing application/json
router.use(bodyParser.urlencoded({extended: true})); // for parsing application/x-www-form-urlencoded

router.restPath = "/target-apk";

router.get('/', function (req, res, next) {
    var logger = Log.getLogger("get target apk");
    //TODO:check the request body
    var targetApkCollection = dbManager.db.collection('TargetApk');
    targetApkCollection.find({}).toArray(function(error, result){
        if(error || !result){
            logger.error(error.name + ": " + error.message);
            res.status(404).json({
                name: error.name,
                message: error.message
            });
        }else{
            res.json(result);
        }
    })
});


/* upload target apk */
router.post('/', upload.single('targetApk'), function (req, res, next) {
    var logger = Log.getLogger("upload target apk");

    //TODO:check the request body, file type check
    var targetApkFile = req.file;
    var targetApkBody = req.body;

    if(targetApkBody.name==undefined) {
        logger.error("target apk: name is required");
        res.status(404).json({
            message: "target apk: name is required"
        });
        return;
    }

    var targetApk = {
        name:targetApkBody.name,
        path:targetApkFile.path,
        fullpath: path.join(path.resolve(__dirname, '..'), targetApkFile.path),
        filename:targetApkFile.filename,
        originalname:targetApkFile.originalname
    };

    var testCodeCollection = dbManager.db.collection('TargetApk');
    testCodeCollection.insertOne(targetApk).then(function(result){
        //location header of the response
        logger.info("test code created: "+ targetApk.toJSON);
        res.location(router.restPath + "/" + targetApk._id);
        res.status(201).end();
    }, function (error){
        logger.error("Save to collection:TargetApk failed");
        res.status(405).end();
    });

});

/* get target apk info */
router.get('/:id', function (req, res, next){
    var tId = req.params.id;
    var logger = Log.getLogger("get TargetApk with id" );
    logger.info(tId);

    //TODO:check the request body
    var obID;
    try {
        obID = new ObjectID(tId);
    } catch (error) {
        var msg = {
            name:"new ObjectID error",
            message:error.toString()
        };
        logger.error(msg);
        res.status(404).json(msg).end();
        return;
    }
    var collection = dbManager.db.collection('TargetApk');
    collection.find({_id: obID}).next(function(error, result){
        if(error){
            logger.error(error.name + ": " + error.message);
            res.status(404).json({
                name: error.name,
                message: error.message
            });
        }else{
            res.json(result);
        }
    })
});

module.exports = router;